package com.google.android.apps.wakemewhere.mapsearch;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

public class SearchTimeout extends TimerTask implements SearchResultCallback {
	private static final Logger logger = Logger.getLogger(SearchTimeout.class.getName());

	private static final int SECONDS_TO_TIMEOUT_AFTER = 10;
	private final Timer timer = new Timer();
	private final SearchResultCallback callback;
	private final Object tag;

	private enum State {
		WAITING, OK, TIME_OUT
	}

	private volatile State state = State.WAITING;

	public SearchTimeout(SearchResultCallback callback, Object tag) {
		logger.info("Timeout counter started");
		timer.schedule(this, 1000 * SECONDS_TO_TIMEOUT_AFTER);
		this.callback = callback;
		this.tag = tag;
	}

	@Override
	public void run() {
		logger.info("Timeout occurred");
		if (state == State.WAITING) {
			timer.cancel();
			state = State.TIME_OUT;
			callback.onSearchResults(new ArrayList<SearchResult>(), tag, null, true);
		}
	}

	public void onSearchResults(List<SearchResult> results, Object tag,
			SearchResultProvider provider, boolean finished) {
		logger.info("Search results came in before time out");
		if (state == State.WAITING) {
			timer.cancel();
			state = State.OK;
		}
		callback.onSearchResults(results, tag, provider, finished);
	}

}
